package com.sevntu.apvs.dModel;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * Class loads tests for the input scheme.
 * 
 * @author <a href="mailto:rd.ryly@gmail.com">Ruslan Diachenko</a>
 */
public class CircuitTestLoader {

	/** Use for log message generation */
	private static final Logger LOG = Logger.getLogger(CircuitTestLoader.class.getName());

	private BufferedReader input;

	/** File name contains a range of tests for scheme */
	private final String FILE_NAME;

	/**
	 * Class constructor which initializes file name.
	 * 
	 * @param fileName
	 *            File name with tests.
	 */
	public CircuitTestLoader(String fileName) {
		this.FILE_NAME = fileName;
	}

	/**
	 * Gets an array of tests for scheme.
	 * 
	 * @param circuitEntryNum
	 *            Number of scheme entries.
	 * @return Array of tests for scheme.
	 * @throws DModelException
	 *             If there's invalid input test.
	 */
	public int[][] getCircuitTest(int circuitEntryNum) throws DModelException {
		List<ArrayList<Integer>> testList = new ArrayList<ArrayList<Integer>>();
		int testNum = 0;
		try {
			input = new BufferedReader(new FileReader(FILE_NAME));
			String str;
			String[] stringValues;
			ArrayList<Integer> intValues;
			int signal;

			while ((str = input.readLine()) != null) {
				stringValues = str.trim().split("\\s+");
				if (stringValues.length != circuitEntryNum) {
					throw new DModelException("Invalid input test #" + (testNum + 1)
							+ "!! Wrong number of input signals!");
				}
				intValues = new ArrayList<Integer>();

				for (String val : stringValues) {
					signal = Integer.parseInt(val);
					if (signal < 0 || signal > 2) {
						throw new DModelException("Invalid input test #" + (testNum + 1)
								+ ". A signal value must be 0, 1 or 2!!");
					}
					intValues.add(signal);
				}
				testList.add(intValues);
				testNum++;
			}
		} catch (IOException e) {
			LOG.error(e);
		} finally {
			if (null != input) {
				try {
					input.close();
				} catch (IOException e) {
					LOG.error(e);
				}
			}
		}
		int[][] circuitTests = new int[testNum][circuitEntryNum];
		for (int i = 0; i < testNum; i++) {
			for (int j = 0; j < circuitEntryNum; j++) {
				circuitTests[i][j] = testList.get(i).get(j);
			}
		}
		LOG.info("Scheme tests were successfuly got.");
		return circuitTests;
	}
}
